import os


def authorize(**kwargs):
    import requests

    cookies = {
        'JSESSIONID': kwargs.get('JSESSIONID'),
        'tempTokenKey': kwargs.get('tempTokenKey'),
    }


    headers = {
        'Host': 'gzmh.zwfw.guizhou.gov.cn',
        'Cache-Control': 'max-age=0',
        'sec-ch-ua': '"Microsoft Edge";v="137", "Chromium";v="137", "Not/A)Brand";v="24"',
        'sec-ch-ua-mobile': '?0',
        'sec-ch-ua-platform': '"Windows"',
        'Origin': 'https://gzmh.zwfw.guizhou.gov.cn',
        'Upgrade-Insecure-Requests': '1',
        'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/137.0.0.0 Safari/537.36 Edg/137.0.0.0',
        'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.7',
        'Sec-Fetch-Site': 'same-origin',
        'Sec-Fetch-Mode': 'navigate',
        'Sec-Fetch-Dest': 'iframe',
        'Referer': 'https://gzmh.zwfw.guizhou.gov.cn/ucenter/simpleLogin?=&response_type=code&client_id=dgov-portal&redirect_uri=https://gzmh.zwfw.guizhou.gov.cn/login/callback.html&version=guizhou&isHLW=true',
        'Accept-Language': 'zh-CN,zh;q=0.9,en;q=0.8,en-GB;q=0.7,en-US;q=0.6',
        'Content-Type': 'application/x-www-form-urlencoded',
    }

    data = {
        'csrf': kwargs.get('csrf'),
        'client_id': 'dgov-portal',
        'redirect_uri': 'https://gzmh.zwfw.guizhou.gov.cn/login/callback.html',
        'response_type': 'code',
        'scope': 'read',
        'state': kwargs.get('state'),
        'busi_uri': '',
        'is_weak_pwd': '0',
        'username': kwargs.get('username'),
        'password': kwargs.get('password'),
        'captcha': kwargs.get('captcha'),
    }

    response = requests.post('https://gzmh.zwfw.guizhou.gov.cn/ucenter/oauth/authorize', cookies=cookies,
                             headers=headers, data=data,allow_redirects=False)
    print('https://gzmh.zwfw.guizhou.gov.cn/ucenter/oauth/authorize')

    print("打印cookies记录")
    print(cookies)
    print(response.headers)
    print("开始保存文件")
    current_dir = os.path.dirname(os.path.abspath(__file__))
    print("当前目录为"+current_dir)
    父目录 = os.path.dirname(current_dir)
    print("父目录为"+父目录)
    构建存储目录=os.path.join(os.path.dirname(父目录),'登录子系统','受理登录过程','jsessionid.json')
    print("构建存储目录"+构建存储目录)
    数据=str(cookies).replace("'", "\"")
    with open(构建存储目录,'w',encoding='utf-8') as f:
        f.write(f'{数据}')
    from 运维工具.登录逻辑.demo09访问重定向地址无需主函数调用 import callback
    Location=response.headers['Location']
    print(Location)
    from 运维工具.登录逻辑.utils.slice_str import slice_between
    code =slice_between(Location,'code=','&')
    callback(Location,**kwargs)
    return {
        "code": code
    }